package com.youlin.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youlin365.health.xdiamond.client.annotation.DiamondValue;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Data
@Service
public class CenterConfig {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @DiamondValue(key = "center.wx.applets")
    private String applets;

    private String active;

    private String appId;

    private String secret;

    public String getActive() {
        if (StringUtils.isBlank(applets)) return null;
        String active = JSON.parseObject(applets).getString("active");
        /*if (StringUtils.isNotBlank(active))
            redisTemplate.opsForValue().set(MyEnum.WX_ACTIVE.getMessage(), active);
        Map apps = JSONObject.parseObject(JSON.parseObject(applets).getString("apps"), Map.class);
        if (apps != null) redisTemplate.opsForHash().putAll(MyEnum.WX_APPLETS.getMessage(), apps);*/
        return active;
    }

    public String getAppId() {
        if (StringUtils.isBlank(applets)) return null;
        JSONObject apps = JSON.parseObject(applets).getJSONObject("apps");
        if (apps == null) return null;
        String active = getActive();
        if (StringUtils.isBlank(active)) return null;
        JSONObject activeJson = apps.getJSONObject(active);
        if (activeJson == null) return null;
        return activeJson.getString("appId");
    }

    public String getSecret() {
        if (StringUtils.isBlank(applets)) return null;
        JSONObject apps = JSON.parseObject(applets).getJSONObject("apps");
        if (apps == null) return null;
        String active = getActive();
        if (StringUtils.isBlank(active)) return null;
        JSONObject activeJson = apps.getJSONObject(active);
        if (activeJson == null) return null;
        return activeJson.getString("secret");
    }

    @Override
    public String toString() {
        return "CenterConfig{" +
                "applets='" + applets + '\'' +
                '}';
    }
}
